package com.study.system.user.filter;

import com.edu.common.entity.User;
import com.edu.common.util.JwtUtils;
import com.edu.common.util.RsaUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * 用户令牌过滤器
 */
@Component
public class TokenValidateFilter extends GenericFilterBean {

    private Logger logger = LoggerFactory.getLogger(TokenValidateFilter.class);

    //过滤请求
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获得请求头中的token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获得请求头中的token
        String token = request.getHeader("Authorization");
        if(token == null){
            logger.error("令牌为空");
        }else{
            try {
                //解析token
                User user = JwtUtils.getUserFromToken(token, RsaUtils.publicKey);
                logger.info("解析成功：{}",user);
                //发验证成功令牌交给security
                UsernamePasswordAuthenticationToken token1 =
                        new UsernamePasswordAuthenticationToken(user.getUsername(),"",
                                AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                SecurityContextHolder.getContext().setAuthentication(token1);
            }catch (Exception ex){
                logger.error("解析失败");
            }
        }
        //请求求放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
